package com.dq.commonutils.jwt;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @project: guli_parent
 * @ClassName: JwtUtil
 * @author: dq
 * @creat: 2022/8/7 12:42
 */
public class JwtUtil {
    private static final String APP_SECRET = "Dq333";
    private static final long EXPIRE = 24 * 60 * 60 * 60 *1000;

    public static String createToken(String userId,String nickName){
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",userId);
        claims.put("nickName",nickName);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, APP_SECRET) // 签发算法，秘钥为jwtToken
                .setClaims(claims) // body数据，要唯一，自行设置
                .setIssuedAt(new Date()) // 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE));// 一天的有效时间
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static Map<String, Object> checkToken(String token){
        try {
            Jwt parse = Jwts.parser().setSigningKey(APP_SECRET).parse(token);
            //获取载荷 中的数据
            return (Map<String, Object>) parse.getBody();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }
}
